package service

import (
	"MyBlogv2/common/HttpCode"
	"MyBlogv2/common/models"
	"MyBlogv2/common/neo4jUtil"
	"MyBlogv2/common/response"
	"fmt"
	"log"

	"github.com/gin-gonic/gin"
)

func SyncAllUsersToNeo4j() error {
	var users []models.User
	result := models.Db.Find(&users)
	if result.Error != nil {
		return fmt.Errorf("查询用户失败: %v", result.Error)
	}

	syncCount := 0
	errorCount := 0
	for _, user := range users {
		err := neo4jUtil.CreateUserNode(user.Id, user.Username)
		if err != nil {
			log.Printf("同步用户 %d 失败: %v", user.Id, err)
			errorCount++
			continue
		}
		syncCount++
	}

	log.Printf("✅ 用户同步完成: 成功 %d 个，失败 %d 个", syncCount, errorCount)
	return nil
}

func SyncAllCategoriesToNeo4j() error {
	var categories []models.Category
	result := models.Db.Find(&categories)
	if result.Error != nil {
		return fmt.Errorf("查询分类失败: %v", result.Error)
	}

	syncCount := 0
	errorCount := 0
	for _, category := range categories {
		err := neo4jUtil.CreateCategoryNode(category.Id, category.CategoryName)
		if err != nil {
			log.Printf("同步分类 %d 失败: %v", category.Id, err)
			errorCount++
			continue
		}
		syncCount++
	}

	log.Printf("✅ 分类同步完成: 成功 %d 个，失败 %d 个", syncCount, errorCount)
	return nil
}

func SyncAllArticlesToNeo4j() error {
	var articles []models.Article
	result := models.Db.Where("is_deleted = 0 AND status = 1").Find(&articles)
	if result.Error != nil {
		return fmt.Errorf("查询文章失败: %v", result.Error)
	}

	syncCount := 0
	errorCount := 0
	for _, article := range articles {
		err := neo4jUtil.CreateArticleNode(article.Id, article.ArticleTitle, article.CategoryId, article.UserId)
		if err != nil {
			log.Printf("同步文章 %d 失败: %v", article.Id, err)
			errorCount++
			continue
		}

		err = neo4jUtil.CreateArticleCategoryRelationship(article.Id, article.CategoryId)
		if err != nil {
			log.Printf("同步文章分类关系 %d 失败: %v", article.Id, err)
		}

		syncCount++
	}

	log.Printf("✅ 文章同步完成: 成功 %d 个，失败 %d 个", syncCount, errorCount)
	return nil
}

func SyncAllLikesToNeo4j() error {
	var likes []models.Like
	result := models.Db.Where("type = 1").Find(&likes)
	if result.Error != nil {
		return fmt.Errorf("查询点赞失败: %v", result.Error)
	}

	syncCount := 0
	errorCount := 0
	for _, like := range likes {
		err := neo4jUtil.CreateLikeRelationship(like.UserId, like.TypeId)
		if err != nil {
			log.Printf("同步点赞关系失败 (用户:%d, 文章:%d): %v", like.UserId, like.TypeId, err)
			errorCount++
			continue
		}
		syncCount++
	}

	log.Printf("✅ 点赞同步完成: 成功 %d 个，失败 %d 个", syncCount, errorCount)
	return nil
}

func SyncAllDataToNeo4j() error {
	log.Println("开始同步数据到 Neo4j...")

	if err := neo4jUtil.CreateIndexes(); err != nil {
		return fmt.Errorf("创建索引失败: %v", err)
	}

	if err := SyncAllUsersToNeo4j(); err != nil {
		return err
	}

	if err := SyncAllCategoriesToNeo4j(); err != nil {
		return err
	}

	if err := SyncAllArticlesToNeo4j(); err != nil {
		return err
	}

	if err := SyncAllLikesToNeo4j(); err != nil {
		return err
	}

	log.Println("✅ 所有数据同步完成！")
	return nil
}

func SyncSingleUser(userId int, username string) error {
	return neo4jUtil.CreateUserNode(userId, username)
}

func SyncSingleArticle(articleId int, title string, categoryId int, userId int) error {
	if err := neo4jUtil.CreateArticleNode(articleId, title, categoryId, userId); err != nil {
		return err
	}
	return neo4jUtil.CreateArticleCategoryRelationship(articleId, categoryId)
}

func SyncLikeAction(userId int, articleId int) error {
	return neo4jUtil.CreateLikeRelationship(userId, articleId)
}

func SyncCancelLikeAction(userId int, articleId int) error {
	return neo4jUtil.DeleteLikeRelationship(userId, articleId)
}

func ClearNeo4jData() error {
	return neo4jUtil.ClearAllData()
}

func SyncAllDataToNeo4jHandler(c *gin.Context) {
	log.Println("开始同步所有数据到 Neo4j...")
	if err := SyncAllDataToNeo4j(); err != nil {
		log.Printf("同步失败: %v", err)
		response.ResponseError(c, HttpCode.FAILURE)
		return
	}
	response.ResponseOK(c, map[string]interface{}{
		"message": "所有数据同步成功",
	})
}

func SyncAllUsersToNeo4jHandler(c *gin.Context) {
	log.Println("开始同步用户数据到 Neo4j...")
	if err := SyncAllUsersToNeo4j(); err != nil {
		log.Printf("同步用户失败: %v", err)
		response.ResponseError(c, HttpCode.FAILURE)
		return
	}
	response.ResponseOK(c, map[string]interface{}{
		"message": "用户数据同步成功",
	})
}

func SyncAllArticlesToNeo4jHandler(c *gin.Context) {
	log.Println("开始同步文章数据到 Neo4j...")
	if err := SyncAllArticlesToNeo4j(); err != nil {
		log.Printf("同步文章失败: %v", err)
		response.ResponseError(c, HttpCode.FAILURE)
		return
	}
	response.ResponseOK(c, map[string]interface{}{
		"message": "文章数据同步成功",
	})
}

func SyncAllLikesToNeo4jHandler(c *gin.Context) {
	log.Println("开始同步点赞数据到 Neo4j...")
	if err := SyncAllLikesToNeo4j(); err != nil {
		log.Printf("同步点赞失败: %v", err)
		response.ResponseError(c, HttpCode.FAILURE)
		return
	}
	response.ResponseOK(c, map[string]interface{}{
		"message": "点赞数据同步成功",
	})
}

func ClearNeo4jDataHandler(c *gin.Context) {
	log.Println("开始清空 Neo4j 数据...")
	if err := ClearNeo4jData(); err != nil {
		log.Printf("清空数据失败: %v", err)
		response.ResponseError(c, HttpCode.FAILURE)
		return
	}
	response.ResponseOK(c, map[string]interface{}{
		"message": "Neo4j数据清空成功",
	})
}
